using Microsoft.Extensions.Logging;
using UniversalAdmin.Application.Services;

namespace UniversalAdmin.Infrastructure.Services;

public class FallbackEmbeddingService : IEmbeddingService
{
    private readonly KimiEmbeddingService _primaryService;
    private readonly MockEmbeddingService _fallbackService;
    private readonly ILogger<FallbackEmbeddingService> _logger;

    public FallbackEmbeddingService(
        KimiEmbeddingService primaryService,
        MockEmbeddingService fallbackService,
        ILogger<FallbackEmbeddingService> logger)
    {
        _primaryService = primaryService;
        _fallbackService = fallbackService;
        _logger = logger;
    }

    public async Task<float[]> GenerateEmbeddingAsync(string text, bool isQuery = false)
    {
        try
        {
            return await _primaryService.GenerateEmbeddingAsync(text, isQuery);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "Primary embedding service failed, falling back to mock service for text: {Text}", text.Substring(0, Math.Min(50, text.Length)));
            return await _fallbackService.GenerateEmbeddingAsync(text, isQuery);
        }
    }

    public async Task<List<float[]>> GenerateEmbeddingsAsync(List<string> texts, bool isQuery = false)
    {
        try
        {
            return await _primaryService.GenerateEmbeddingsAsync(texts, isQuery);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "Primary embedding service failed, falling back to mock service for {Count} texts", texts.Count);
            return await _fallbackService.GenerateEmbeddingsAsync(texts, isQuery);
        }
    }
}